package com.gopay.bis.manager.bank.bcdl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.bank.IcbcConstants;
import com.gopay.common.domain.bank.BcdlMessage;
import com.gopay.common.domain.bank.bcdl.BcdlPacket;
import com.gopay.common.domain.bank.icbc.bcdl.pay.IcbcMessageData;
import com.gopay.common.domain.bank.icbc.bcdl.pay.IcbcPacketMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.businesses.BcdlService;

public class IcbcBcdlManager {
	@Resource(name = "icbcBcdlService")
	private BcdlService icbcBcdlService;
	
	@Resource(name = "icbcConfig")
    private Map<String, String> icbcConfig;
	public Object eft(BcdlMessage msg) throws GopayException {
		IcbcMessageData msgSnd =buildMessage(msg);
		BankLogUtils.printBcdlEftManagerSendLog(msgSnd);
		Object o=icbcBcdlService.eft(msgSnd);
		BankLogUtils.printBcdlEftManagerReturnLog(msgSnd);
		return o;
	}
	
    public Object eft(BcdlPacket bcdlPacket) throws GopayException {
        IcbcPacketMessage packetMsgSnd = new IcbcPacketMessage();
        BeanUtils.copyProperties(bcdlPacket, packetMsgSnd);
        packetMsgSnd.setTranDate(TransUtil.getTransTime().substring(0, 8));
        packetMsgSnd.setTranTime(TransUtil.getSendTime().substring(8));
        packetMsgSnd.setOnlBatF(IcbcConstants.ONLBATF); // 联机标志位
        packetMsgSnd.setSettleMode(IcbcConstants.SETTLEMODE_SINGLE);
        packetMsgSnd.setTotalNum(bcdlPacket.getBcdlMessages().size() + ""); // 指令笔数

        packetMsgSnd.setSignTime(TransUtil.getSendTime()); // 签名时间
        packetMsgSnd.setReqReserved1("");
        packetMsgSnd.setReqReserved2("");

        List<BcdlMessage> bcdlList = bcdlPacket.getBcdlMessages(); // 批量发起订单list
        if (null != bcdlList && bcdlList.size() > 0) {
            List<IcbcMessageData> icbcMessageList = new ArrayList<IcbcMessageData>();
            BigDecimal totalAmount = new BigDecimal("0"); // 批量订单总金额
            for (int i = 0; i < bcdlList.size(); i++) {
                // 循环拼装批量订单所需数据
                IcbcMessageData msgSnd = buildMessage(bcdlList.get(i));
                totalAmount = totalAmount.add(new BigDecimal(msgSnd.getPayAmt()));
                icbcMessageList.add(msgSnd);
            }
            packetMsgSnd.setTotalAmt(totalAmount.toString());
            packetMsgSnd.setIcbcMessageDatas(icbcMessageList);
        }
        
        BankLogUtils.printBcdlEftManagerSendLog(packetMsgSnd);
        Object o = icbcBcdlService.packetEft(packetMsgSnd);
        BankLogUtils.printBcdlEftManagerReturnLog(packetMsgSnd);
        return o;
    }
	
	private IcbcMessageData buildMessage(BcdlMessage msg) {
		IcbcMessageData msgSnd = new IcbcMessageData();
		String isSameCity = msg.getIsSameCity()+""; // 同城/异地标志
		msgSnd.setOpName("NCPayentOp");
		String transTime =TransUtil.getTransTime();
		msgSnd.setTranDate(transTime.substring(0,8));
		msgSnd.setTranTime(TransUtil.getSendTime().substring(8));
		msgSnd.setfSeqno(msg.getGopayBankOrderNo()); // 每次提交的值应不一样(itenId+时间戳)
		msgSnd.setOnlBatF(IcbcConstants.ONLBATF); // 联机标志位
		msgSnd.setSettleMode(IcbcConstants.SETTLEMODE_SINGLE);
		msgSnd.setTotalNum("1");
		msgSnd.setTotalAmt(msg.getAmount().movePointRight(2).toString()); // 没有小数点 分为单位
		msgSnd.setSignTime(TransUtil.getSendTime()); // 签名时间
		msgSnd.setReqReserved1("");
		msgSnd.setReqReserved2("");
		msgSnd.setISeqno(msg.getItemId()+""); // 指令序列号
		 //加急标志  记账处理方式
		if("1".equals(msg.getEmergency()+"")) {
			msgSnd.setPayType(IcbcConstants.PAY_TYPE_NORMAL);	// 不加急
		} else if ("0".equals(msg.getEmergency()+"")) {
			msgSnd.setPayType(IcbcConstants.PAY_TYPE_FAST);	// 加急
		}else if("2".equals(msg.getEmergency()+"")){
			msgSnd.setPayType(IcbcConstants.SUPER_ONLINE_BANKING);	// 跨行快汇
		}
		msgSnd.setRecAccNo(msg.getRecvBankAcctNum()); // 对方账号
		msgSnd.setRecAccNameCN(msg.getRecvBankAcctName()); // 对方账号名称（中文名称、英文名称二者必输其一）
		if(msgSnd.getPayType().equals(IcbcConstants.SUPER_ONLINE_BANKING)||msg.getSysIOFlg()==2){
			msgSnd.setSysIOFlg(IcbcConstants.SYS_OUT_FLAG);
		}else{
			msgSnd.setSysIOFlg(IcbcConstants.SYS_IN_FLAG);
		}
		System.out.println("=============="+msg.getGopayBankOrderNo()+"==="+isSameCity);
		// 同城异地标示 
		if ("1".equals(isSameCity+"")) {
			msgSnd.setSameCity(IcbcConstants.IS_SAME_CITY); // 同城
		} else if ("2".equals(isSameCity+"")) {
			msgSnd.setSameCity(IcbcConstants.IS_NOT_SAME_CITY); // 异地
		}else{
			msgSnd.setSameCity(IcbcConstants.IS_SAME_CITY);
		}
		 //对公对私标示 
		if ("1".equals(msg.getDcblType()+"")) {
			msgSnd.setProp(IcbcConstants.PROP_TO_C); // 对公
		} else if ("2".equals(msg.getDcblType()+"")) {
			msgSnd.setProp(IcbcConstants.PROP_TO_P); // 对私
		}
		msgSnd.setRecCityName(msg.getRecvBankCityName()); // 收款方所在城市名称（跨行必填）
		msgSnd.setRecBankName(msg.getPbocBankName()); // 交易对方银行名称
		msgSnd.setRecBankNo(msg.getPobcBankCode()); // 交易对方行行号
		msgSnd.setCurrType("001"); // 币种
		msgSnd.setUseCN(msg.getGopayBankOrderNo()); // 用途中文描述(如需跨行实时到帐此项最多10个字符.超长则落地处理)
		msgSnd.setPayAmt(msg.getAmount().movePointRight(2).toString()); // 金额
		msgSnd.setPostScript(msg.getGopayBankOrderNo());
		msgSnd.setSummary(msg.getGopayBankOrderNo()); // 摘要、备注（对私情况下,用途和备注不能同时为空）
		msgSnd.setLabel(msg.getLabel()); //标识对应前置机
		return msgSnd;
	}

	public Object query(Object obj) throws GopayException {
		BcdlMessage msg = (BcdlMessage) obj;
		IcbcMessageData msgSnd = new IcbcMessageData();
		msgSnd.setTranDate(TransUtil.getCurrentDateStr());
		msgSnd.setTranTime(TransUtil.getSendTime().substring(8));
		msgSnd.setfSeqno(msg.getOrderId()); // 每次提交的值应不一样  
		msgSnd.setQryfSeqno(msg.getOrderId()); // 待查指令
		BankLogUtils.printBcdlManagerQuerySendLog(msgSnd);
		IcbcMessageData o=(IcbcMessageData)icbcBcdlService.query(msgSnd);
		BankLogUtils.printBcdlManagerQueryReturnLog(msgSnd);
		if(StringUtils.isNotBlank(o.getPayAmt())){
			o.setAmount(new BigDecimal(o.getPayAmt()));
		}
		return o;
	}
	
    public Object query(BcdlPacket bcdlPacket) throws GopayException {
        IcbcPacketMessage packetMsgSnd = new IcbcPacketMessage();
        BeanUtils.copyProperties(bcdlPacket, packetMsgSnd);
        packetMsgSnd.setTranDate(TransUtil.getCurrentDateStr());
        packetMsgSnd.setTranTime(TransUtil.getSendTime().substring(8));

        List<BcdlMessage> queryList = bcdlPacket.getBcdlMessages(); // 批量查询订单list
        if (null != queryList && queryList.size() > 0) {
            List<IcbcMessageData> icbcQueryList = new ArrayList<IcbcMessageData>();
            for (int i = 0; i < queryList.size(); i++) {
                // 循环拼装批量查询所需数据
                IcbcMessageData msgSnd = new IcbcMessageData();
                BeanUtils.copyProperties((BcdlMessage) queryList.get(i), msgSnd);
                icbcQueryList.add(msgSnd);
            }
            packetMsgSnd.setIcbcMessageDatas(icbcQueryList);
        }
        BankLogUtils.printBcdlManagerQuerySendLog(packetMsgSnd);

        IcbcPacketMessage queryRes = (IcbcPacketMessage) icbcBcdlService.queryPacket(packetMsgSnd);
        BankLogUtils.printBcdlManagerQueryReturnLog(queryRes);
        return queryRes;
    }
	
	public Object queryBal(Object obj) throws GopayException {
		BcdlMessage msg = (BcdlMessage) obj;
		IcbcMessageData msgSnd = new IcbcMessageData();
		msgSnd.setTranDate(TransUtil.getCurrentDateStr());
		msgSnd.setTranTime(TransUtil.getSendTime().substring(8));
		msgSnd.setfSeqno(msg.getOrderId()); // 每次提交的值应不一样  
		msgSnd.setCurrType("001"); // 币种
		msgSnd.setReqReserved3("");
		msgSnd.setBlFlag("");
		msgSnd.setSynFlag("");
		msgSnd.setAcctSeq("");
		BankLogUtils.printBcdlManagerQueryBalanceSendLog(msgSnd);
		IcbcMessageData o=(IcbcMessageData)icbcBcdlService.queryBalance(msgSnd);
		o.setBalance(o.getUsableBalance());
		BankLogUtils.printBcdlManagerQueryBalanceReturnLog(msgSnd);
		if(StringUtils.isNotBlank(o.getPayAmt())){
			o.setAmount(new BigDecimal(o.getPayAmt()));
		}
		return o;
	}
	
    public Object qryAcctDetail(Object obj) throws GopayException {
        BcdlMessage msg = (BcdlMessage) obj;
        IcbcMessageData msgSnd = new IcbcMessageData();
        msgSnd.setTransTime(msg.getOrderDate());
//        msgSnd.setQuerySize(Integer.parseInt(msg.getSpecial2())); // 查询次数
        msgSnd.setTranDate(TransUtil.getCurrentDateStr());
        msgSnd.setTranTime(TransUtil.getSendTime().substring(8));
        msgSnd.setfSeqno(TransUtil.getCurrentDateStr() + getShortUuid()); // 每次提交的值应不一样
        msgSnd.setBeginDate(msg.getOrderDate().substring(0, 8)); // 交易起始日期
        msgSnd.setEndDate(msg.getOrderDate().substring(0, 8)); // 交易截止日期
        msgSnd.setMinAmount("0"); // 发生额下线
        msgSnd.setMaxAmount(icbcConfig.get("ICBC.BCDL.AMOUNT.LIMIT")); // 发生额上线
        msgSnd.setCurrType("001"); // 币种
        msgSnd.setNextTag(msg.getSpecial()); // 查询下页标识
        BankLogUtils.printBcdlManagerQueryAcctDetailSendLog(msgSnd);
        IcbcMessageData detailRes = (IcbcMessageData) icbcBcdlService.queryAcctDetail(msgSnd);
        return detailRes;
    }
    
    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z" };

    public static String getShortUuid() {
        StringBuffer stringBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int strInteger = Integer.parseInt(str, 16);
            stringBuffer.append(chars[strInteger % 0x3E]);
        }

        return stringBuffer.toString();
}
}
